package org.rooster.genetic.monitor;

import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by IntelliJ IDEA.
 * User: manorama
 * Date: 7/14/12
 * Time: 4:47 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProgressWithTimeMonitor extends Thread {
    
    public static ScheduledExecutorService executorService;
    
    private Vector<Double> fitnessValueVector;
    private int TIME_TO_BEGIN = 0;
    private int TIME_PERIOD;

    private boolean MAX_PROGRESS_REACHED = false;

    /**
     * If there is no progress in fitness value with the time period
     * this Progress Monitor set the MAX_PROGRESS_REACHED to true.
     * @param vector  the Vector containing fitness values
     * @param timePeriod the time period within which the fitness to be constant (this need to be specified in seconds)
     */
    public ProgressWithTimeMonitor(Vector<Double> vector, int timePeriod) {
        this.fitnessValueVector = vector;
        this.TIME_PERIOD = timePeriod;
    }

    @Override
    public void run() {

        double previousFitness, newFitness, progress;

        while (true) {

            try {
                sleep(TIME_TO_BEGIN);
                if(fitnessValueVector.size() > 0) {
                    previousFitness = fitnessValueVector.lastElement();
                    sleep(TIME_PERIOD * 1000);
                    newFitness = fitnessValueVector.lastElement();
                    progress = (newFitness - previousFitness);
                    if(progress == 0) {
                        MAX_PROGRESS_REACHED = true;
                        System.out.println("Progress Monitor : NO PROGRESS WITHIN " + TIME_PERIOD + " SECONDS");
                        stop();
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (NoSuchElementException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isMAX_PROGRESS_REACHED() {
        return MAX_PROGRESS_REACHED;
    }

    //    @Override
//    public void run() {
//        if (executorService == null) {
//            executorService = Executors.newScheduledThreadPool(1);
//            try {
//                executorService.scheduleAtFixedRate(new Runnable() {
//                        public void run() {
////                            if(fitnessValueVector)
//                        }
//                    }, 4, 4, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
